package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AjaxAuthenticationFilter extends FormAuthenticationFilter {
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        e.printStackTrace();
        response.setContentType("application/json;charset=utf-8");
        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(false);

        if (e instanceof UnknownAccountException){
            jsonResult.setMsg("用户错误");
        }else if (e instanceof IncorrectCredentialsException){
            jsonResult.setMsg("密码错误");
        }else {
            jsonResult.setMsg("老板跑路");
        }

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e1) {
            e1.printStackTrace();
            jsonResult.setMsg(e.getMessage());
        }
        writer.write(JSON.toJSONString(jsonResult));

        return false;
    }

    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        JsonResult jsonResult = new JsonResult(true,"完美");
        //登录excuteLogin(request,response)方法在他爸里面
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e1) {
            e1.printStackTrace();
            jsonResult.setMsg(e1.getMessage());
        }
        writer.write(JSON.toJSONString(jsonResult));
        return false;
    }
}
